package com.spring.appservice.web.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.fasterxml.jackson.databind.util.JSONPObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mangofactory.swagger.annotations.ApiIgnore;
import com.spera.genutil.TokenUtil;
import com.spring.appservice.web.model.AppExam;
import com.spring.appservice.web.model.Baby;
import com.spring.appservice.web.model.CommitExamGetNext;
import com.spring.appservice.web.model.Quest;
import com.spring.appservice.web.service.AppQuestService;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.core.util.UDate;
import com.spring.security.web.dao.JedisCache;

/**
 * Created by wojunyu on 2015/7/26.
 */
@Controller
@RequestMapping(value = "/appQuest")
@ApiIgnore
public class AppQuestController {
	static Logger logger = Logger.getLogger(AppQuestController.class.getName());

	@Resource
	private JedisCache jedisCache;
	@Resource
	private AppQuestService appQuestService;

	/**
	 * 出题接口,并返回第一题
	 * 
	 * @param request
	 * @param age_group
	 * @param rule_id
	 * @param exam_type
	 * @return
	 */
	@RequestMapping(value = "/getExam_old")
	@ResponseBody
	public Object getExam_old(HttpServletRequest request, String age_group,
			String rule_id, String exam_type) {
//		User u = (User) request.getSession().getAttribute(Contents.USER_INFO);
		Map<String, Object> retMap = new HashMap<String, Object>();
		try {
			if (!ApplicationUtils.isNotNull(age_group)
					|| !ApplicationUtils.isNotNull(rule_id)) {
				retMap.put("status", "0");
				retMap.put("msg", "年龄段规则必须选择");
				return retMap;
			}
			Map<String, Object> m = new HashMap<String, Object>();
			m.put("age_group", age_group);
			m.put("rule_id", rule_id);
			// 按出题规则查询出规则对应的8元题目
			List<Map> ruleList = appQuestService.selectRuleDetail(m);
			if (ruleList == null && ruleList.size() != 0) {
				retMap.put("status", "0");
				retMap.put("msg", "规则获取失败");
				return retMap;
			}

			// 规则主键
			String rule_setting_id = ApplicationUtils.Object2String(ruleList
					.get(0).get("rule_setting_id"));

			// 试卷主键
			String UID = ApplicationUtils.randomUUID();
			String exam_title = "随机试卷" + new Date();
			String totalnum = appQuestService.CreateExamByRule(UID,
					rule_setting_id, exam_title, ruleList, "", "");

			AppExam ex = new AppExam();
			ex.setExam_id(UID);
			ex.setExam_title(exam_title);
			ex.setQuestion_total_num(totalnum);

			m.put("exam_id", UID);
			m.put("question_index", "1");

			List<Quest> examList = appQuestService.selectExamQuestById(m);

			retMap.put("dataset", ex);
			retMap.put("question", examList);
			retMap.put("status", "1");
			retMap.put("msg", "取数成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return retMap;
	}

	/**
	 * 出题接口,并返回第一题 v1.0
	 * 
	 * @param request
	 * @param age_group
	 * @param rule_id
	 * @param exam_type
	 * @return
	 */
	@RequestMapping(value = "/getExam")
	@ResponseBody
	public Object getExam(/* HttpServletRequest request, */String token,
			String c_baby_id,String baby_birthday, String callback) {
		logger.info("AppQuestController----->getExam,token:"+token+",begin:"+UDate.getDate("yyyy-MM-dd HH:mm:ss"));
		// User u = (User)
		// request.getSession().getAttribute(Contents.USER_INFO);
		Map<String, Object> retMap = new HashMap<String, Object>();
		String user_id = "";
		try {
			Map<String, Object> b = TokenUtil.checkToken(token,jedisCache);
			if (b != null) {
				if (ApplicationUtils.isNotNull(callback)) {
					return new JSONPObject(callback, b);
				} else {
					return b;
				}
			}
			user_id = jedisCache.hget(token,TokenUtil.USER_ID);
			if (!ApplicationUtils.isNotNull(c_baby_id)) {
				retMap.put("status", "0");
				retMap.put("msg", "孩子必须选择");
				if (ApplicationUtils.isNotNull(callback)) {
					return new JSONPObject(callback, retMap);
				} else {
					return retMap;
				}
			}
			if (!ApplicationUtils.isNotNull(baby_birthday)) {
				retMap.put("status", "0");
				retMap.put("msg", "孩子生日必须传输");
				if (ApplicationUtils.isNotNull(callback)) {
					return new JSONPObject(callback, retMap);
				} else {
					return retMap;
				}
			}
			
			
			
			

			Map<String, Object> m = new HashMap<String, Object>();
			m.put("c_user_id", c_baby_id);
			m.put("baby_birthday", baby_birthday);
			// m.put("age_group", age_group);
			// m.put("rule_id", rule_id);
			// 按出题规则查询出规则对应的8元题目

			List<Map> ruleList = appQuestService.selectRuleDetail(m);
			if (ruleList == null || ruleList.size() == 0) {
				retMap.put("status", "0");
				retMap.put("msg", "规则获取失败");
				if (ApplicationUtils.isNotNull(callback)) {
					return new JSONPObject(callback, retMap);
				} else {
					return retMap;
				}
			}

			// 规则主键
			String rule_setting_id = ApplicationUtils.Object2String(ruleList
					.get(0).get("rule_setting_id"));
			// 根据babyid查询

			// 试卷主键
			String UID = ApplicationUtils.randomUUID();

			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			String exam_title = "随机试卷" + df.format(new Date());
//			logger.info("begin:"+UDate.getDate("yyyy-MM-dd HH:mm:ss"));
			String totalnum = appQuestService.CreateExamByRule(UID,
					rule_setting_id, exam_title, ruleList, user_id, c_baby_id);
//			logger.info("end:"+UDate.getDate("yyyy-MM-dd HH:mm:ss"));
			AppExam ex = new AppExam();
			ex.setExam_id(UID);
			ex.setExam_title(exam_title);
			ex.setQuestion_total_num(totalnum);

			m.put("exam_id", UID);
			m.put("question_index", "1");

			List<Quest> examList = appQuestService.selectExamQuestById(m);

			retMap.put("dataset", ex);
			retMap.put("question", examList);
			retMap.put("status", "1");
			retMap.put("msg", "取数成功");
			logger.info("AppQuestController----->getExam,token:"+token+",end:"+UDate.getDate("yyyy-MM-dd HH:mm:ss"));
		} catch (Exception e) {
			e.printStackTrace();
			retMap.put("status", "0");
			retMap.put("msg", "系统异常");
			logger.info("AppQuestController----->getExam,token:"+token+",end:"+UDate.getDate("yyyy-MM-dd HH:mm:ss"));
		}
		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, retMap);
		} else {
			return retMap;
		}
	}

	/**
	 * 提交答案,并生成下一题
	 * 
	 * @param exam_id
	 * @param question_index
	 * @param question_id
	 * @param user_option
	 * @return
	 */
	/*
	 * @RequestMapping(value = "/commitExam")
	 * 
	 * @ResponseBody public Object commitExam(String exam_id, String
	 * question_index, String question_id, String user_option) { return null; }
	 */

	/**
	 * 察看历史接口
	 * 
	 * @param user_id
	 * @param baby_id
	 * @param page_index
	 * @param page_size
	 * @return
	 */
	@RequestMapping(value = "/getExamHistory")
	@ResponseBody
	public Object getExamHistory(String token, String baby_id, String skip,
			String rows, String callback) {
		logger.info("AppQuestController----->getExamHistory");
		Map<String, Object> chectToken = TokenUtil.checkToken(token,jedisCache);

		if (chectToken != null) {

			if (ApplicationUtils.isNotNull(callback)) {
				return new JSONPObject(callback, chectToken);
			} else {
				return chectToken;
			}

			// return chectToken;
		}

		String user_id = jedisCache.hget(token,TokenUtil.USER_ID);

		Map<String, Object> m = new HashMap<String, Object>();

		if (user_id == null || skip == null || rows == null) {

			m.put("status", "0");
			m.put("msg", "请输入正确的参数");
			if (ApplicationUtils.isNotNull(callback)) {
				return new JSONPObject(callback, m);
			} else {
				return m;
			}
		}

		try {
			System.out.println("getExamHistory");
			System.out.println(baby_id + "baby_id");

			// long baby_id_l=Long.parseLong(baby_id);
			Long skip_l = Long.parseLong(skip);
			Long rows_l = Long.parseLong(rows);

			ArrayList a = appQuestService.selectgetExamHistory(user_id,
					baby_id, skip_l, rows_l);
			// ArrayList a=new ArrayList();
			List<Quest> questList = (List<Quest>) a.get(1);

			m.put("dataset", questList);
			m.put("status", "1");
			m.put("count", (String) a.get(0));
			m.put("msg", "取数成功");

		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(m.size());
		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}

	/**
	 * 察看历史接口
	 * 
	 * @param user_id
	 * @param baby_id
	 * @param page_index
	 * @param page_size
	 * @return
	 */
	/*
	 * @RequestMapping(value = "/getExamHistoryJsonP")
	 * 
	 * @ResponseBody public Object getExamHistoryJsonP(String user_id, String
	 * baby_id, String skip, String rows,String callback) { Map<String,Object> m
	 * = new HashMap<String,Object>();
	 * 
	 * 
	 * 
	 * 
	 * 
	 * if(user_id==null||skip==null||rows==null){
	 * 
	 * m.put("status", "0"); m.put("msg", "请输入正确的参数");
	 * if(ApplicationUtils.isNotNull(callback)){ return new
	 * JSONPObject(callback, m); }else{ return m; } }
	 * 
	 * 
	 * Long skip_l=Long.parseLong(skip); Long rows_l=Long.parseLong(rows);
	 * 
	 * 
	 * try { ArrayList a= appQuestService.selectgetExamHistory(user_id, baby_id,
	 * skip_l, rows_l); List<Quest> questList = (List<Quest> )a.get(1);
	 * 
	 * m.put("dataset", questList); m.put("status", "1");
	 * m.put("count",(String)a.get(0)); m.put("msg", "取数成功");
	 * 
	 * } catch (Exception e) { e.printStackTrace(); }
	 * System.out.println(m.size()); return new JSONPObject(callback,m); }
	 */
	/**
	 * 察看历史8元接口
	 * 
	 * @param score_id
	 * @return
	 */
	@RequestMapping(value = "/getExamHistoryDetail")
	@ResponseBody
	public Object getExamHistoryDetail(String exam_id, String callback,
			String token) {
		logger.info("AppQuestController----->getExamHistoryDetail");
		Map<String, Object> chectToken = TokenUtil.checkToken(token,jedisCache);

		if (chectToken != null) {

			if (ApplicationUtils.isNotNull(callback)) {
				return new JSONPObject(callback, chectToken);
			} else {
				return chectToken;
			}

			// return chectToken;
		}

		System.out.println(exam_id + "score_id");
		Map<String, Object> m = new HashMap<String, Object>();
		try {
			List<Quest> questList = appQuestService
					.getExamHistoryDetail(exam_id);
			m.put("dataset", questList);
			m.put("status", "1");
			m.put("msg", "取数成功");

		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("Detail");
		System.out.println(m.size());

		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}

	/**
	 * 察看历史8元接口
	 * 
	 * @param score_id
	 * @return
	 */
	/*
	 * @RequestMapping(value = "/getExamHistoryDetailJsonP")
	 * 
	 * @ResponseBody public Object getExamHistoryDetailJsonP(String
	 * exam_id,String callback) { System.out.println(exam_id + "score_id");
	 * Map<String,Object> m = new HashMap<String,Object>(); try { List<Quest>
	 * questList = appQuestService.getExamHistoryDetail(exam_id);
	 * m.put("dataset", questList); m.put("status", "1"); m.put("msg", "取数成功");
	 * 
	 * } catch (Exception e) { e.printStackTrace(); }
	 * System.out.println("Detail"); System.out.println(m.size());
	 * 
	 * return new JSONPObject(callback,m); }
	 */
	/**
	 * 历史明细每8元题目
	 * 
	 * @param score_id
	 * @param quest_type_id
	 * @return
	 */
	@RequestMapping(value = "/getExamHisDetailComp")
	@ResponseBody
	public Object getExamHisDetailComp(String exam_id, String quest_type_id,
			String callback, String token) {
		logger.info("AppQuestController----->getExamHisDetailComp");
		Map<String, Object> chectToken = TokenUtil.checkToken(token,jedisCache);

		if (chectToken != null) {

			if (ApplicationUtils.isNotNull(callback)) {
				return new JSONPObject(callback, chectToken);
			} else {
				return chectToken;
			}

			// return chectToken;
		}

		Map<String, Object> m = new HashMap<String, Object>();
		try {
			List<Quest> questList = appQuestService
					.getExamHistoryDetailComplete(exam_id, quest_type_id);
			m.put("dataset", questList);
			m.put("status", "1");
			m.put("msg", "取数成功");

		} catch (Exception e) {
			e.printStackTrace();
		}
		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}

	/**
	 * 历史明细每8元题目
	 * 
	 * @param score_id
	 * @param quest_type_id
	 * @return
	 */
	/*
	 * @RequestMapping(value = "/getExamHisDetailCompJsonP")
	 * 
	 * @ResponseBody public Object getExamHisDetailCompJsonP(String exam_id,
	 * String quest_type_id,String callback) { Map<String,Object> m = new
	 * HashMap<String,Object>(); try { List<Quest> questList =
	 * appQuestService.getExamHistoryDetailComplete(exam_id, quest_type_id);
	 * m.put("dataset", questList); m.put("status", "1"); m.put("msg", "取数成功");
	 * 
	 * } catch (Exception e) { e.printStackTrace(); } return new
	 * JSONPObject(callback,m); }
	 */

	// 答题提交并生成下一题
	@RequestMapping(value = "/commitExam")
	@ResponseBody
	public Object commitExam(String c_baby_id,String exam_id, String question_index,
			String question_id, String user_option_id, String next_index,
			String callback, String token) {
		logger.info("AppQuestController----->commitExam");
		Map<String, Object> chectToken = TokenUtil.checkToken(token,jedisCache);

		if (chectToken != null) {

			if (ApplicationUtils.isNotNull(callback)) {
				return new JSONPObject(callback, chectToken);
			} else {
				return chectToken;
			}
		}
		
		String user_id = jedisCache.hget(token,TokenUtil.USER_ID);

		Map<String, Object> m = new HashMap<String, Object>();
		try {
			List<CommitExamGetNext> questList = appQuestService.commitExam(user_id,c_baby_id,
					exam_id, question_index, question_id, user_option_id,
					next_index);
			m.put("dataset", questList);
			m.put("status", "1");
			m.put("msg", "取数成功");

		} catch (Exception e) {
			e.printStackTrace();
		}
		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}

	// 答题提交并生成下一题
	/*
	 * @RequestMapping(value = "/commitExamJsonP")
	 * 
	 * @ResponseBody public Object commitExamJsonP(String exam_id, String
	 * question_index, String question_id, String user_option_id, String
	 * next_index, String callback) { Map<String,Object> m = new
	 * HashMap<String,Object>(); try { List<CommitExamGetNext> questList =
	 * appQuestService.commitExam(exam_id, question_index, question_id,
	 * user_option_id, next_index); m.put("dataset", questList); m.put("status",
	 * "1"); m.put("msg", "取数成功");
	 * 
	 * } catch (Exception e) { e.printStackTrace(); } return new
	 * JSONPObject(callback, m); }
	 * 
	 * /** 查看当前完成答题情况
	 * 
	 * @param exam_id
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getNotCompExamHis")
	@ResponseBody
	public Object getNotCompExamHis(String exam_id, String callback,
			String token) {
		logger.info("AppQuestController----->getNotCompExamHis");
		Map<String, Object> chectToken = TokenUtil.checkToken(token,jedisCache);

		if (chectToken != null) {

			if (ApplicationUtils.isNotNull(callback)) {
				return new JSONPObject(callback, chectToken);
			} else {
				return chectToken;
			}

			// return chectToken;
		}

		Map<String, Object> m = new HashMap<String, Object>();
		try {
			ArrayList a = appQuestService.getNotCompleteExamHistory(exam_id);
			List<CommitExamGetNext> questList = (List<CommitExamGetNext>) a
					.get(1);
			System.out.println(questList.toString());
			System.out.println(questList.size());

			m.put("dataset", questList);
			m.put("count", (String) a.get(0));
			m.put("status", "1");
			m.put("msg", "取数成功");

		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(m.toString());
		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}

	/**
	 * 查看当前完成答题情况
	 * 
	 * @param exam_id
	 * @return
	 */
	/*
	 * @RequestMapping(value = "/getNotCompExamHisJsonP")
	 * 
	 * @ResponseBody public Object getNotCompExamHisJsonP(String exam_id, String
	 * callback) { Map<String,Object> m = new HashMap<String,Object>(); try {
	 * ArrayList a=appQuestService.getNotCompleteExamHistory(exam_id);
	 * List<CommitExamGetNext> questList =(List<CommitExamGetNext>)a.get(1);
	 * System.out.println(questList.toString());
	 * System.out.println(questList.size());
	 * 
	 * m.put("dataset", questList); m.put("count",(String)a.get(0));
	 * m.put("status", "1"); m.put("msg", "取数成功");
	 * 
	 * } catch (Exception e) { e.printStackTrace(); }
	 * System.out.println(m.toString()); return new JSONPObject(callback, m); }
	 */
	/**
	 * 试卷提交
	 * 
	 * @param exam_id
	 * @return
	 */
	@RequestMapping(value = "/commitExamAll")
	@ResponseBody
	public Object commitExamAll(String exam_id, String callback, String token) {
		logger.info("AppQuestController----->commitExamAll");
		Map<String, Object> chectToken = TokenUtil.checkToken(token,jedisCache);

		if (chectToken != null) {

			if (ApplicationUtils.isNotNull(callback)) {
				return new JSONPObject(callback, chectToken);
			} else {
				return chectToken;
			}

			// return chectToken;
		}
		Map<String, Object> m = new HashMap<String, Object>();
		try {
			int a = appQuestService.commitExamAll(exam_id);

			if (a == 1) {
				m.put("msg", "插入成功");
				m.put("status", "1");
			} else {
				m.put("msg", "请勿重复提交");
				m.put("status", "0");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(m.toString());
		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}

	/**
	 * 试卷提交
	 * 
	 * @param exam_id
	 * @return
	 */
	/*
	 * @RequestMapping(value = "/commitExamAllJsonP")
	 * 
	 * @ResponseBody public Object commitExamAllJsonP(String exam_id, String
	 * callback) { Map<String,Object> m = new HashMap<String,Object>(); try {
	 * int a = appQuestService.commitExamAll(exam_id);
	 * 
	 * if (a == 1) { m.put("msg", "插入成功"); m.put("status", "1"); } else {
	 * m.put("msg", "请勿重复提交"); m.put("status", "0"); }
	 * 
	 * 
	 * } catch (Exception e) { e.printStackTrace(); }
	 * System.out.println(m.toString()); return new JSONPObject(callback, m); }
	 */

	//@RequestMapping(value = "/getBabyByParent")
	@ResponseBody
	public Object getBabyByParent(String token, String callback) {
		logger.info("AppQuestController----->getBabyByParent");
		Map<String, Object> s = TokenUtil.checkToken(token,jedisCache);

		if (s != null) {
			if (ApplicationUtils.isNotNull(callback)) {
				return new JSONPObject(callback, s);
			} else {
				return s;
			}
		}

		String c_user_id = jedisCache.hget(token,TokenUtil.USER_ID);

		Map<String, Object> m = new HashMap<String, Object>();
		try {
			List<Baby> al = appQuestService.getBabyByParent(c_user_id);

			m.put("msg", "查询成功");
			m.put("status", "1");
			m.put("dataset", al);

		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(m.toString());
		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}

}
